package com.agent.crm.imagecache;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.BitmapFactory;

import com.agent.crm.config.AppConfig;
import com.agent.crm.util.SDCardHelper;

/**
 * 图片加载辅助类，类中提供了加载本地图片loadSDImage（）操作、downloadImageWithUrl网络请求操作
 * 
 * @author Yek Mobile
 * 
 */
public class ImageHelper {

	/** 缓存图片的绝对路�?*/
	public String mCachePath = "";

	/** 压缩质量参数 */
	public static final int COMPRESS_QUALITY = 100;

	public ImageHelper() {
		mCachePath = AppConfig.CACHE_PATH;
	}

	/**
	 * 加载本地图片,<font color='red'>此方法被遗弃了，不建议使用，请使用重载方�?
	 * {@link #loadSDImage(String, String)}</font>
	 * 
	 * @param imgUrl 图片下载地址
	 * @return Bitmap 请求成功后的图片对象
	 * 
	 */
	public Bitmap loadSDImage(String imgUrl) {
		Bitmap bitmap = null;
		FileInputStream fis = null;
		try {
			String imgName = imgUrl.substring(imgUrl.lastIndexOf("/") + 1);
			if (SDCardHelper.getInstance().sdCardMounted()) {
				File imgFile = new File(AppConfig.CACHE_PATH + imgName);
				if (!imgFile.exists()) {
					return null;
				}
				fis = new FileInputStream(imgFile);
				byte[] bytes = stream2Bytes(fis);
				bitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
			}
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (fis != null) {
				try {
					fis.close();
					fis = null;
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return bitmap;
	}

	/**
	 * 加载本地图片
	 * 
	 * @param imgUrl 图片地址
	 * @param SaveImagepath
	 *            图片保存路径
	 * @return Bitmap
	 * 
	 */
	public Bitmap loadSDImage(String imgUrl, String SaveImagepath) {
		Bitmap bitmap = null;
		FileInputStream fis = null;
		try {
			String imgName = imgUrl.substring(imgUrl.lastIndexOf("/") + 1);
			if (SDCardHelper.getInstance().sdCardMounted()) {
				File imgFile = new File(SaveImagepath + imgName);
				if (!imgFile.exists()) {
					return null;
				}
				fis = new FileInputStream(imgFile);
				byte[] bytes = stream2Bytes(fis);
				bitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
			}
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (fis != null) {
				try {
					fis.close();
					fis = null;
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return bitmap;
	}

	/**
	 * 加载网络图片
	 * 
	 * @param info
	 * @return Bitmap
	 */
	public Bitmap downloadImageWithUrl(String imgUrl) {
		Bitmap bitmap = null;
		InputStream is = null;
		try {
			URL url = new URL(imgUrl);
			if (url == null || url.getContent() == null) {
				return null;
			}
			HttpURLConnection conn = (HttpURLConnection) url.openConnection();
			conn.setDoInput(true);
			conn.connect();
			if (conn.getResponseCode() == 200) {
				is = conn.getInputStream();
				int length = (int) conn.getContentLength();
				if (length != -1) {
					byte[] imgData = new byte[length];
					byte[] temp = new byte[512];
					int readLen = 0;
					int destPos = 0;
					while ((readLen = is.read(temp)) > 0) {
						System.arraycopy(temp, 0, imgData, destPos, readLen);
						destPos += readLen;
					}
					bitmap = BitmapFactory.decodeByteArray(imgData, 0,
							imgData.length);

				}
			}
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (is != null) {
				try {
					is.close();
					is = null;
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return bitmap;
	}

	/**
	 * 将流转成字节数组
	 * 
	 * @param is
	 * @return
	 * @throws IOException
	 */
	public byte[] stream2Bytes(InputStream is) throws IOException {
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		byte[] buffer = new byte[1024];
		int length = 0;
		while ((length = is.read(buffer, 0, 1024)) != -1) {
			baos.write(buffer, 0, length);
		}
		baos.flush();
		return baos.toByteArray();
	}

	/**
	 * 获得图片的占用空间大�?
	 * 
	 * @param bmp
	 * @return 图片占用的字节数
	 */
	private int getImageSize(Bitmap bmp) {
		try {
			if (bmp == null) {
				return 0;
			}
			ByteArrayOutputStream baos = new ByteArrayOutputStream();
			bmp.compress(CompressFormat.PNG, COMPRESS_QUALITY, baos);
			int size = baos.size();
			baos.flush();
			baos.close();
			return size;
		} catch (IOException e) {
			e.printStackTrace();
		}
		return 0;
	}

	/**
	 * 将图片存入sd�?
	 * 
	 * @param imgUrl
	 *            图片网络地址
	 * @param bmp
	 *            网络请求过来的bitmap对象
	 * @param SaveImagepath
	 *            图片保存到sdcard 的路�?
	 * @return 存储结果
	 */
	public String storeImageToSdCard(String imgUrl, Bitmap bmp,
			String SaveImagepath) {
		if (!SDCardHelper.getInstance().sdCardMounted()) {
			return "Memory card not found";
		}
		if (SDCardHelper.getInstance().getAvailableSdCardSize() < getImageSize(bmp)) {
			return "Not enough memory";
		}
		FileOutputStream fos = null;
		try {
			File dir = new File(SaveImagepath);
			if (!dir.exists()) {
				// LogManager.info(mCachePath);
				if (!dir.mkdirs()) {
					// LogManager.error("Failed to create dir ! ");
				}
			}

			String fileName = imgUrl.substring(imgUrl.lastIndexOf("/") + 1);
			File imgFile = new File(dir, fileName);
			if (imgFile.exists()) {
				imgFile.delete();
			}
			if (imgFile.createNewFile()) {
				fos = new FileOutputStream(imgFile);
				bmp.compress(CompressFormat.PNG, COMPRESS_QUALITY, fos);
			} else {
				// LogManager.error("Failed to create file ! ");
			}
		} catch (FileNotFoundException e) {
			e.printStackTrace();
			return "Save failed";
		} catch (IOException e) {
			e.printStackTrace();
			return "Save failed";
		} finally {
			try {
				if (fos != null) {
					fos.flush();
					fos.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
				return "Save failed";
			}
		}
		return "Save successfully";
	}

}
